package session;

import com.alibaba.fastjson.JSONObject;
import entity.data.DocFile;
import entity.data.DocFolder;
import entity.inte.mycloud.token.AppAccessTokenRequest;
import entity.inte.mycloud.token.AppAccessTokenResponse;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SessionData {
	/** 最大重试次数，请求失败时的最大重试次数 */
	public static final int MAX_RETRY_COUNT = 10;
	/**
	 * 根目录
	 */
	public static final DocFolder ROOT_FOLDER = new DocFolder();
	/** 绝对路径对云文档对象的映射 */
	public static final ConcurrentHashMap<String, DocFile> DOC_FILE_MAP = new ConcurrentHashMap<>();
	public static final AppAccessTokenRequest APP_ACCESS_TOKEN_REQUEST;
	public static String ROOT_FOLDER_TOKEN;

	/** 总文件数 * 3 */
	public static final AtomicInteger FILE_COUNT = new AtomicInteger(0);


	/** 拷贝文件的文件名前缀，希望不要与已有文件重名 */
	public static final String FILE_PREFIX = ".LarkMarkdownUploadTemp";
	public static final String URL_PREFIX = "https://LarkMarkdownUploadTemp";
	public static final String BASE_URL = "https://open.feishu.cn/open-apis";
	public static final String APP_ACCESS_TOKEN_URL = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal";

	static {
		try (InputStream inputStream = SessionData.class.getResourceAsStream("/config.properties")) {
			if (inputStream != null) {
				Properties properties = new Properties();
				properties.load(inputStream);
				ROOT_FOLDER_TOKEN = properties.getProperty("rootFolderToken", "");
				APP_ACCESS_TOKEN_REQUEST = new AppAccessTokenRequest(
						properties.getProperty("appId", ""),
						properties.getProperty("appSecret", "")
				);
			} else {
				ROOT_FOLDER_TOKEN = "";
				APP_ACCESS_TOKEN_REQUEST = new AppAccessTokenRequest("", "");
			}

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 自建应用获取 app_access_token
	 * <p>
	 * 连接超时就重试
	 */
	public static AppAccessTokenResponse getAppAccessToken() {
		try {
			String jsonData = Jsoup.connect(APP_ACCESS_TOKEN_URL)
					.header("Content-Type", "application/json; charset=utf-8")
					.requestBody(JSONObject.toJSONString(APP_ACCESS_TOKEN_REQUEST))
					.ignoreContentType(true)
					.timeout(10000)
					.post()
					.text();
			return JSONObject.parseObject(jsonData, AppAccessTokenResponse.class);
		} catch (ConnectException | SocketTimeoutException e) { //连接超时就重试
			return getAppAccessToken();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
